package qiniu

import (
	"blog_go/config"
	"blog_go/global"
	"blog_go/utils"
	"bytes"
	"context"
	"errors"
	"fmt"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"time"
)

// 获取上传的token
func GetToken(q config.Qiniu) string {
	accessKey := q.AccessKey
	secretKey := q.SecretKey
	bucket := q.Bucket
	policy := storage.PutPolicy{
		Scope: bucket,
	}
	mac := qbox.NewMac(accessKey, secretKey)
	uplaodTokne := policy.UploadToken(mac)
	return uplaodTokne
}

// 获取上传的配置
func GetCfg(q config.Qiniu) storage.Config {
	cfg := storage.Config{}
	// 空间对应的机器号
	zone, _ := storage.GetRegionByID(storage.RegionID(q.Zone))
	cfg.Zone = &zone
	// 是否使用http域名
	cfg.UseHTTPS = false
	// 上传使用cdn加速
	cfg.UseCdnDomains = false
	return cfg
}

// 文件上传
func UploadImage(data []byte, imageName string, prefix string) (filePath string, err error) {
	if !global.Conf.Qiniu.Enable {
		return "filePath", errors.New("请开启七牛云")
	}
	qiniu := global.Conf.Qiniu
	if qiniu.AccessKey == "" || qiniu.SecretKey == "" {
		return "", errors.New("请配置七牛accessKey和secretKey")
	}
	if float64(len(data))/1024/1024 > qiniu.Size {
		return "", errors.New("文件超过设定大小")
	}
	token := GetToken(qiniu)
	cfg := GetCfg(qiniu)
	uploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	extra := storage.PutExtra{
		Params: map[string]string{},
	}
	dataLen := int64(len(data))
	// 获取当前时间
	formatNow := time.Now().Format(utils.FORMAT2)
	key := fmt.Sprintf("%s/%s_%s", prefix, formatNow, imageName)
	err = uploader.Put(context.Background(), &ret, token, key, bytes.NewReader(data), dataLen, &extra)
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%s/%s", qiniu.CDN, ret.Key), nil
}
